package org.catdroid.bomba.server.servlet;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.catdroid.bomba.server.Constants;
import org.catdroid.bomba.server.GameManager;
import org.catdroid.bomba.server.bean.Player;
import org.catdroid.bomba.server.bean.Players.PlayerNotFoundException;

@SuppressWarnings("serial")
public class StartServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		GameManager gm=new GameManager();
		resp.setContentType("application/json");
		if (gm.isStartReady()) {
			resp.getWriter().println(Constants.JSON_OK);
		}else{
			resp.getWriter().println(Constants.JSON_KO);
		}
	}
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		

		String id= req.getParameter("id");
		
		
		Player player;
		GameManager gm=new GameManager();
		
		boolean ok=true;
		try {
			player=gm.getPlayers().getPlayer(id);
			player.setReady(true);
			ok=true;
			if (gm.isStartReady()) {
				gm.startGame();
			}
		} catch (PlayerNotFoundException e) {
			ok=false;
		}
		resp.setContentType("application/json");
		if (ok) {
			resp.getWriter().println(Constants.JSON_OK);
		}else{
			resp.getWriter().println(Constants.JSON_KO);
		}
		
	}
}
